package com.qihoo.finance.backup;

import com.qihoo.finance.backup.reader.IteratorBackReader;
import com.qihoo.finance.backup.writer.BackWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

/**
 * 迭代备份器
 */
public class IteratorBacker extends Backer {

    private static final Logger logger = LogManager.getLogger(IteratorBacker.class);

    private IteratorBackReader backReader;

    private BackWriter backWriter;

    public void setBackReader(IteratorBackReader backReader) {
        this.backReader = backReader;
    }

    public void setBackWriter(BackWriter backWriter) {
        this.backWriter = backWriter;
    }

    @Override
    Result backup() {
        try {
            backWriter.connect();
            logger.info("backWriter connected");
            while (backReader.hasNext()) {
                if (!this.isRunning()) {
                    return ResultUtils.success();
                }
                List<String> next = backReader.next();
                Result result = backWriter.write(next);
                if (result.hasError()) {
                    logger.info("backWriter error, result is {}", result);
                    return result;
                }
            }
            logger.info("backWriter write finish");
            return ResultUtils.success();
        } finally {
            backWriter.close();
            backReader.close();
            this.stop();
        }
    }
}
